/*
 * Version 0.4 by Steffen Schuhmann
 *      Constants are now static final
 *      StringReader is now StringLineReader
 *      Improve import 
 * 
 * Version 0.5 by Andreas Dier
 *      Again added different Exceptions
 *      Decreased import
 *      Resolve Errors
 */
package ueb14.htw.io;

import java.io.*;



/**
 * Class StringReader
 * 
 * @author Andreas Dier, Steffen Schuhmann 
 * @version 0.5
 */
public class StringLineReader {
    
    // Constants
    
    private static final String STRING_IS_NULL      = "Given String is null";
    private static final String STRING_IS_EMPTY     = "Given String is empty";
    private static final String FILE_NOT_FOUND      = "This file was not found";
    private static final String NOT_A_FILE          = "This is not a file";
    private static final String NO_READ_ACCESS      = "You do not have read access for this file";
    private static final String NO_WRITE_ACCESS     = "You do not have write access for this file";
    private static final String READ_ERROR          = "Fehler beim Einlesen";
    private static final String EMPTY               = " ";

    private LineNumberReader in;

    public StringLineReader(String fileName) throws IOException {
        if(fileName == null)
            throw new NullPointerException(STRING_IS_NULL);
            if(EMPTY.equals(fileName))
                throw new StringIsEmptyException(STRING_IS_EMPTY);
			
		File file = new File(fileName);
		
		if(!file.exists())
			throw new FileNotFoundException(FILE_NOT_FOUND);
		if(!file.isFile()) 
			throw new IsNoFileException(NOT_A_FILE);
		if(!file.canRead())
			throw new CanNotReadException(NO_READ_ACCESS);
		if(!file.canWrite())
			throw new CanNotWriteException(NO_WRITE_ACCESS);
			
        in = new LineNumberReader(new BufferedReader(new FileReader(fileName))); 

    }

	
	public String read(int lineNumber) throws IOException {
        String lineString;
        try {
				in.setLineNumber(lineNumber);
				return lineString = in.readLine();
            
        } catch (RuntimeException e) {
            throw new IOException(READ_ERROR, e);
        } 
    }

    public void close() throws IOException {
        in.close();
        in = null;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (in != null)
            close();
    }
}

